<?

require_once("mysql.php");

function google_extract_suggest_results($goog) {

    $suggest = array();

    $c = 0;

    while ($c = strpos($goog, "data=\"", $c+1)) {
    
        $d = strpos($goog, "\"", $c+6);
    
        $s =  substr($goog, $c+6, $d-($c+6));
    
        array_push($suggest, $s);
    }
	
    return array_slice($suggest, 0, 4);
     
}

function google_suggest($s) {

    $q = "SELECT * FROM suggest WHERE query='%s'";
    $q = sprintf($q, ESC($s));
    $r = MYSQL_Q($q);
    $c = mysql_num_rows($r);

    if ($c == 1) {

        $row = mysql_fetch_assoc($r);

        $php = json_decode(stripslashes($row['results']));

        MYSQL_Q("UPDATE suggest SET count=".($row['count']+1)." WHERE query='".ESC($s)."'");

        return ($php);

    } else if ($c == 0) {

        $SEARCH = "http://google.com/complete/search?output=toolbar&q=".urlencode($s);
    
        $xml = (file_get_contents($SEARCH));
    
        //TODO:  make sure reply is sane
    
        $php =  google_extract_suggest_results($xml);  


        $q = "INSERT INTO suggest VALUES ('%s', '%s', UNIX_TIMESTAMP(NOW()), 0)";
        $q = sprintf($q, ESC($s), ESC(json_encode($php)));
        MYSQL_Q($q);

    
        return ($php);

    }

}

 
/*
 * Echo the search results out to STDOUT only if the client is requesting the 
 * suggest.php script.  This is required to distinguish from the case where 
 * the client invokes a script other than suggest.php but that script includes 
 * suggest.php  
 */
if (strpos($_SERVER['PHP_SELF'], "suggest.php") > 0) {
    echo json_encode(google_suggest($_GET['search']));
}


?>
